
import asyncio
import threading
from typing import Any, List, Union
from aioredis import Redis
from redis import Redis
from fastapi import Header, Depends, Form, Request, APIRouter, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from initialization.dbInit import get_db_session, get_async_session
from initialization.redisInit import get_async_redis, get_sync_redis
from model.afferentEntitys import PutMenuInfo, AfferentCase, AfferentCaseGroup, AfferenScheduledTask, UserInfo, RoleInfo
from model.entitys import get_sync_db, Execut, SyncSession
from service import powerService, webService, caseService
from service.apiService import ApiService
from service.loginService import login
from threadHandle.threadHandle import ThreadHandleCase
from utils import business
from utils.results import unified_return
from variable import case_thread_pool, application_thread_pool

auth = APIRouter(tags=["token认证"])
power = APIRouter(tags=["权限管理"])
case = APIRouter(tags=["用例管理"])
task = APIRouter(tags=["任务管理"])
document = APIRouter(tags=["文件管理"])
application = APIRouter(tags=["app测试工具"])

@auth.post("/auth/login", summary="用户登录认证")
async def sing(user_info: UserInfo, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await login(session, user_info)

@power.put("/power/addUser")
async def addUser(user: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.add_user(session, user)

@power.put("/power/addRole")
async def addRole(role: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.add_role(session, role)

@power.put("/power/addRoleV1")
async def addRoleV1(role: RoleInfo, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.add_role_v1(session, role)

@power.post("/power/updateUser")
async def updateUser(user: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.update_user(session, user)

@power.get("/power/queryMenuByRoleId")
async def queryMenuByRoleId(role_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.query_menu_by_role_id(session, role_id)

@power.get("/power/queryMenuByRoleIdAsync")
async def queryMenuByRoleIdAsync(role_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.query_menu_by_role_id_async(session, role_id)

@power.post("/power/updateRoleMenuByRoleId")
async def updateRoleMenuByRoleId(role_id: str, menuList: List[PutMenuInfo], session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.update_role_menu_by_role_id_api(session, role_id, menuList, 0)

@power.post("/power/updateRoleMenuByRoleIdAsync")
async def updateRoleMenuByRoleIdAsync(role_id: str, menuList: List[dict], session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.update_role_menu_by_role_id_api_async(session, role_id, menuList)

@power.get("/power/queryMenuByUserId")
async def queryMenuByUserId(user_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.query_menu_by_user_id(session, user_id)

@power.get("/power/queryMenuByUserIdAsync")
async def queryMenuByUserIdAsync(user_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.query_menu_by_user_id_async(session, user_id)

@power.get("/power/getUserMenu")
async def getUserMenu(Authorization: str = Header(None), session: AsyncSession = Depends(get_db_session)) -> Any:
    return await powerService.get_user_menu(session, Authorization)

@case.put("/case/addCaseGroup")
async def addCaseGroup(case_group: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.add_case_group(session, case_group)

@case.post("/case/updateCaseGroup")
async def updateCaseGroup(case_group: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.update_case_group(session, case_group)

@case.post("/case/findCaseGroup")
async def findCaseGroup(case_group: AfferentCaseGroup, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.find_case_group(session, case_group)

@case.delete("/case/deleteCaseGroup/{case_group_id}")
async def deleteCaseGroup(case_group_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    tem = await webService.judge_existence_case(session, case_group_id)
    if tem is None:
        return await webService.delete_case_group(session, case_group_id)
    else:
        return tem

@case.put("/case/addCase")
async def addCase(ac: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.add_case(session, ac)

@case.post("/case/updateCase")
async def updateCase(ac: dict, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.update_case(session, ac)

@case.post("/case/findCase")
async def findCase(ac: AfferentCase, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.find_case(session, ac)

@case.delete("/case/deleteCase/{case_id}")
async def deleteCase(case_id: str, session: AsyncSession = Depends(get_db_session)) -> Any:
    return await webService.delete_case(session, case_id)

@case.post("/case/runCase")
def runCase(gain_id: Union[str, List[str]], redis: Redis = Depends(get_sync_redis), api: ApiService = Depends(ApiService)) -> Any:
    result = webService.judge_running(redis, gain_id)
    if result:
        return result

    case_thread_pool.submit(caseService.run_case, api, gain_id)
    # threading.Thread(target=caseService.run_case, args=(api, gain_id)).start()

    return {"message": "启动成功,用例列表可查看结果", "code": 200, "data": None}

@case.post("/case/batchRunCaseAsync")
def batchRunCaseGroupAsync(gain_id: List[str], redis: Redis = Depends(get_sync_redis)) -> Any:
    business.clear_running_case(redis, gain_id)

    for case_group_id in gain_id:
        case_thread_pool.submit(caseService.run_case, ApiService(), case_group_id)
        # threading.Thread(target=caseService.run_case, args=(ApiService(), case_group_id)).start()

    return {"message": "启动成功,用例列表可查看结果", "code": 200, "data": None}

@case.post("/case/batchRunCase")
def batchRunCaseGroup(gain_id: List[str], redis: Redis = Depends(get_sync_redis), api: ApiService = Depends(ApiService)) -> Any:
    business.clear_running_case(redis, gain_id)

    case_thread_pool.submit(webService.batch_run_case, api, gain_id)
    # threading.Thread(target=webService.batch_run_case, args=(api, gain_id)).start()

    return {"message": "启动成功,用例列表可查看结果", "code": 200, "data": None}

@task.put("/task/addSched")
def addSched(afst: dict, session: SyncSession = Depends(get_sync_db)):
# async def addSched(afst: dict, session: AsyncSession = Depends(get_db_session)):
    return webService.add_sched(session, afst)
    # return await webService.add_sched(session, afst)

@task.delete("/task/deleteSched/{st_id}")
def deleteSched(st_id: str, session: SyncSession = Depends(get_sync_db)):
# async def deleteSched(st_id: str, session: AsyncSession = Depends(get_db_session)):
    return webService.delete_sched(session, st_id)
    # return await webService.delete_sched(session, st_id)

@task.post("/task/updateSched")
def updateSched(afst: dict, session: SyncSession = Depends(get_sync_db)):
# async def updateSched(afst: dict, session: AsyncSession = Depends(get_db_session)):
    return webService.update_sched(session, afst)
    # return await webService.update_sched(session, afst)

@task.post("/task/findSched")
async def findSched(afst: AfferenScheduledTask, session: AsyncSession = Depends(get_db_session)):
    return await webService.find_sched(session, afst)

@task.post("/task/startPauseSched")
def startPauseSched(afst: AfferenScheduledTask, session: SyncSession = Depends(get_sync_db)):
# async def startPauseSched(afst: AfferenScheduledTask, session: AsyncSession = Depends(get_db_session)):
    return webService.start_pause_sched(session, afst)
    # return await webService.start_pause_sched(session, afst)

@document.post("/file/uploadCases")
def uploadCases(files: List[UploadFile] = File(...)):
    return webService.upload_cases(files)

@case.post("/case/commandLineExecute")
def commandLineExecute(command: dict):
    case_thread_pool.submit(webService.command_line_execute, command["cmd"])

    return {"message": "启动成功,稍后可查看报告", "code": 200, "data": None}

@case.get("/case/multipleFileHandle")
def multipleFileHandle(folder: str):
    case_thread_pool.submit(ThreadHandleCase().multiple_file_handle, folder)

    return {"message": "启动成功,稍后可查看报告", "code": 200, "data": None}

@application.post("/application/pressure")
def appPressure(info: dict, redis: Redis = Depends(get_sync_redis)) -> Any:
    if redis.exists(info["package"]):
        return {"message": "该用app正在测试中,请稍后再试", "code": 400, "data": None}

    application_thread_pool.submit(webService.app_pressure, redis, info)

    return {"message": "启动成功,正在实时监控", "code": 200, "data": None}

@application.post("/application/commandPressure")
def appCommandPressure(command: dict) -> Any:
    application_thread_pool.submit(webService.monkey_command, command)

    return {"message": "启动成功,正在实时监控", "code": 200, "data": None}






































